package com.thkj.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.thkj.interceptor.Permissions;
import com.thkj.service.StatisticalService;
import com.thkj.util.RequestUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import dp.R;
import dp.dao.PagingList;
import com.thkj.framework.base.BaseController;

@RestController
@RequestMapping("/backstage/statistical")
public class StatisticalAction extends BaseController {

	@Resource
	StatisticalService statisticalService;

	@Permissions("statistical_001")
	@RequestMapping("")
	public ModelAndView index() {
		return new ModelAndView("statistical/index");
	}

	/**
	 * 统计图页面初始化数据
	 * 
	 * @return
	 */
	// @Permissions("statistical_001")
	@RequestMapping("/getStatistical")
	public R getStatistical() {
		Map map = statisticalService.getStatistical();
		map.put("productTop", statisticalService.queryProductTop());
		return R.success(map);
	}

	/**
	 * 获得图表数据
	 * 
	 * @return
	 */
	// @Permissions("statistical_001")
	@RequestMapping("/loadEchartsData")
	public R loadEchartsData() {
		Map map = new HashMap();
		List<Map> echartsDataForMoney = statisticalService.loadEchartsDataForMoney();
		List<String> xData = new ArrayList<String>();
		List<String> y1 = new ArrayList<String>();
		List<String> y2 = new ArrayList<String>();
		List<String> y3 = new ArrayList<String>();
		List<String> y4 = new ArrayList<String>();
		DecimalFormat df = new DecimalFormat("#");
		for (Map map2 : echartsDataForMoney) {
			xData.add(map2.get("dateStr").toString());
			y1.add(df.format(Double.parseDouble(map2.get("orderAmount").toString())));
			y2.add(df.format(Double.parseDouble(map2.get("serviceAmount").toString())));
			y3.add(df.format(Double.parseDouble(map2.get("purchaseMoney").toString())));
			y4.add(df.format(Double.parseDouble(map2.get("orderWeight").toString())));
		}
		map.put("xData", xData);
		map.put("y1", y1);
		map.put("y2", y2);
		map.put("y3", y3);
		map.put("y4", y4);
		
		List<Map> echartsDataForMoney2 = statisticalService.loadEchartsDataForMoneyByMonth();
		List<String> xData2 = new ArrayList<String>();
		List<String> y12 = new ArrayList<String>();
		List<String> y22 = new ArrayList<String>();
		List<String> y32 = new ArrayList<String>();
		List<String> y42 = new ArrayList<String>();
		for (Map map2 : echartsDataForMoney2) {
			xData2.add(map2.get("monthStr").toString());
			y12.add(df.format(Double.parseDouble(map2.get("orderAmount").toString())));
			y22.add(df.format(Double.parseDouble(map2.get("serviceAmount").toString())));
			y32.add(df.format(Double.parseDouble(map2.get("purchaseMoney").toString())));
			y42.add(df.format(Double.parseDouble(map2.get("orderWeight").toString())));
		}
		map.put("xData2", xData2);
		map.put("y12", y12);
		map.put("y22", y22);
		map.put("y32", y32);
		map.put("y42", y42);
		return R.success(map);
	}
	
	/**
	 * 计划调度
	 * 
	 * @return
	 */
	@Permissions("statistical_002")
	@RequestMapping("/dispatch")
	public ModelAndView dispatch() {
		return new ModelAndView("statistical/dispatch");
	}

	@RequestMapping("/loadDispatchData")
	public R loadDispatchData(HttpServletRequest request) {
		Map<String, Object> param = RequestUtil.getParameterMap(request);
		// PagingList<Map> list = statisticalService.loadDispatchData(param, page,
		// size);
		List<Map> list = statisticalService.loadDispatchData(param);
		return R.success(list);
	}

	/**
	 * 销售报表
	 * 
	 * @return
	 */
	@Permissions("statistical_003")
	@RequestMapping("/salesReport")
	public ModelAndView salesReport() {
		return new ModelAndView("statistical/salesReport");
	}

	/**
	 * 销售报表数据
	 * 
	 * @param request
	 * @param page
	 * @param size
	 * @return
	 */
	@Permissions("statistical_003")
	@RequestMapping("/querySalesReport")
	public R querySalesReport(HttpServletRequest request, int page, int size) {
		Map<String, Object> param = RequestUtil.getParameterMap(request);
		PagingList<Map> list = statisticalService.querySalesReport(param, page, size);
		list.getList().forEach(map -> {
			map.put("serviceFee",
					new BigDecimal(Double.parseDouble(map.get("serviceFee").toString())
							* Double.parseDouble(map.get("totalWeight").toString()) / 100)
									.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			map.put("allMoney",
					new BigDecimal(Double.parseDouble(map.get("totalMoney").toString())
							+ Double.parseDouble(map.get("serviceFee").toString()))
									.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
		});
		return R.success(list);
	}

	/**
	 * 导出销售报表
	 * 
	 * @throws IORuntimeException
	 * @throws IOException
	 */
	@Permissions("statistical_003")
	@RequestMapping("/exportSalesReport")
	public void exportSalesReport() throws IORuntimeException, IOException {
		Map<String, Object> param = RequestUtil.getParameterMap(this.getRequest());
		HttpServletResponse response = this.getResponse();
		PagingList<Map> list = statisticalService.querySalesReport(param, 1, Integer.MAX_VALUE);
		list.getList().forEach(map -> {
			map.put("serviceFee",
					new BigDecimal(Double.parseDouble(map.get("serviceFee").toString())
							* Double.parseDouble(map.get("totalWeight").toString()) / 100)
									.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			map.put("allMoney",
					new BigDecimal(Double.parseDouble(map.get("totalMoney").toString())
							+ Double.parseDouble(map.get("serviceFee").toString()))
									.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
		});
		// 通过工具类创建writer，创建xlsx格式
		ExcelWriter writer = ExcelUtil.getWriter(true);
		writer.setColumnWidth(-1, 20); // 设置列宽
		writer.setOnlyAlias(true); // 只保留别名字段
		// 自定义标题别名
		writer.addHeaderAlias("dateStr", "日期");
		writer.addHeaderAlias("buyerName", "客户名称");
		writer.addHeaderAlias("totalMoney", "销售额");
		writer.addHeaderAlias("serviceFee", "服务费");
		// writer.addHeaderAlias("allMoney", "总金额");

		// 一次性写出内容，使用默认样式
		writer.write(list.getList());
		String fileName = URLEncoder.encode("销售报表", "utf-8") + DateUtil.format(new Date(), "yyyy-MM-dd");
		response.setContentType("application/vnd.ms-excel;charset=utf-8");

		// test.xlsx是弹出下载对话框的文件名，不能为中文，中文请自行编码
		response.setHeader("Content-Disposition", "attachment;filename= " + fileName + ".xlsx");
		response.setHeader("Cache-Control", "private");
		response.setHeader("Pragma", "private");
		response.setHeader("Content-Type", "application/force-download");
		// out为OutputStream，需要写出到的目标流
		writer.flush(response.getOutputStream());
		// 关闭writer，释放内存
		writer.close();
	}

	/**
	 * 采购报表
	 * 
	 * @return
	 */
	@Permissions("statistical_004")
	@RequestMapping("/purchaseReport")
	public ModelAndView purchaseReport() {
		return new ModelAndView("statistical/purchaseReport");
	}

	/**
	 * 采购报表数据
	 * 
	 * @param request
	 * @param page
	 * @param size
	 * @return
	 */
	@Permissions("statistical_004")
	@RequestMapping("/queryPurchaseReport")
	public R queryPurchaseReport(HttpServletRequest request, int page, int size) {
		DecimalFormat df = new DecimalFormat("#.00");
		Map<String, Object> param = RequestUtil.getParameterMap(request);
		PagingList<Map> list = statisticalService.queryPurchaseReport(param, page, size);
		list.getList().forEach(item -> {
			try {
				if (item.get("num") != null && item.get("finalPrice") != null) {
					double money = Double.parseDouble(item.get("num").toString())
							* Double.parseDouble(item.get("finalPrice").toString());
					item.put("money", df.format(money));
				}
			} catch (Exception e) {
			}

		});
		return R.success(list);
	}

	/**
	 * 导出采购报表
	 * 
	 * @throws IORuntimeException
	 * @throws IOException
	 */
	@Permissions("statistical_004")
	@RequestMapping("/exportPurchaseReport")
	public void exportPurchaseReport() throws IORuntimeException, IOException {
		DecimalFormat df = new DecimalFormat("#.00");
		Map<String, Object> param = RequestUtil.getParameterMap(this.getRequest());
		HttpServletResponse response = this.getResponse();
		PagingList<Map> list = statisticalService.queryPurchaseReport(param, 1, 9999);
		list.getList().forEach(item -> {
			if (item.get("finalPrice") == null) {
				item.put("finalPrice", "-");
			}
			try {
				if (item.get("num") != null && item.get("finalPrice") != null) {
					double money = Double.parseDouble(item.get("num").toString())
							* Double.parseDouble(item.get("finalPrice").toString());
					item.put("money", df.format(money));
				}
			} catch (Exception e) {
			}
		});
		// 通过工具类创建writer，创建xlsx格式
		ExcelWriter writer = ExcelUtil.getWriter(true);
		writer.setColumnWidth(-1, 20); // 设置列宽
		writer.setOnlyAlias(true); // 只保留别名字段
		// 自定义标题别名
		writer.addHeaderAlias("dateStr", "日期");
		writer.addHeaderAlias("supplierName", "供应商");
		writer.addHeaderAlias("productName", "商品名称");
		writer.addHeaderAlias("num", "数量");
		writer.addHeaderAlias("finalPrice", "单价");
		writer.addHeaderAlias("money", "金额");

		// 一次性写出内容，使用默认样式
		writer.write(list.getList());
		String fileName = URLEncoder.encode("采购报表", "utf-8") + DateUtil.format(new Date(), "yyyy-MM-dd");
		response.setContentType("application/vnd.ms-excel;charset=utf-8");

		// test.xlsx是弹出下载对话框的文件名，不能为中文，中文请自行编码
		response.setHeader("Content-Disposition", "attachment;filename= " + fileName + ".xlsx");
		response.setHeader("Cache-Control", "private");
		response.setHeader("Pragma", "private");
		response.setHeader("Content-Type", "application/force-download");
		// out为OutputStream，需要写出到的目标流
		writer.flush(response.getOutputStream());
		// 关闭writer，释放内存
		writer.close();
	}

	/**
	 * 应收汇总
	 * 
	 * @return
	 */
	@Permissions("statistical_004")
	@RequestMapping("/summaryReceivable")
	public ModelAndView summaryReceivable() {
		return new ModelAndView("statistical/summaryReceivable");
	}

	/**
	 * 应收汇总数据
	 * 
	 * @param request
	 * @param page
	 * @param size
	 * @return
	 */
	@Permissions("statistical_004")
	@RequestMapping("/querySummaryReceivable")
	public R querySummaryReceivable(HttpServletRequest request) {
		Map<String, Object> param = RequestUtil.getParameterMap(request);
		List<Map> list = statisticalService.querySummaryReceivable(param);
		return R.success(list);
	}

	/**
	 * 导出应收汇总
	 * 
	 * @throws IORuntimeException
	 * @throws IOException
	 */
	@Permissions("statistical_004")
	@RequestMapping("/exportSummaryReceivable")
	public void exportSummaryReceivable() throws IORuntimeException, IOException {
		Map<String, Object> param = RequestUtil.getParameterMap(this.getRequest());
		HttpServletResponse response = this.getResponse();
		List<Map> list = statisticalService.querySummaryReceivable(param);
		// 通过工具类创建writer，创建xlsx格式
		ExcelWriter writer = ExcelUtil.getWriter(true);
		writer.setColumnWidth(-1, 20); // 设置列宽
		writer.setOnlyAlias(true); // 只保留别名字段
		// 自定义标题别名
		writer.addHeaderAlias("name", "客户名称");
		writer.addHeaderAlias("orderAmount", "订单金额");
		writer.addHeaderAlias("serviceAmount", "服务费用");
		writer.addHeaderAlias("totalAmount", "总金额");

		// 一次性写出内容，使用默认样式
		writer.write(list);
		String fileName = URLEncoder.encode("应收汇总", "utf-8") + DateUtil.format(new Date(), "yyyy-MM-dd");
		response.setContentType("application/vnd.ms-excel;charset=utf-8");

		// test.xlsx是弹出下载对话框的文件名，不能为中文，中文请自行编码
		response.setHeader("Content-Disposition", "attachment;filename= " + fileName + ".xlsx");
		response.setHeader("Cache-Control", "private");
		response.setHeader("Pragma", "private");
		response.setHeader("Content-Type", "application/force-download");
		// out为OutputStream，需要写出到的目标流
		writer.flush(response.getOutputStream());
		// 关闭writer，释放内存
		writer.close();
	}

	/**
	 * 应付汇总
	 * 
	 * @return
	 */
	@Permissions("statistical_004")
	@RequestMapping("/summaryPayable")
	public ModelAndView summaryPayable() {
		return new ModelAndView("statistical/summaryPayable");
	}

	/**
	 * 应付汇总数据
	 * 
	 * @param request
	 * @param page
	 * @param size
	 * @return
	 */
	@Permissions("statistical_004")
	@RequestMapping("/querySummaryPayable")
	public R querySummaryPayable(HttpServletRequest request) {
		Map<String, Object> param = RequestUtil.getParameterMap(request);
		List<Map> list = statisticalService.querySummaryPayable(param);
		return R.success(list);
	}

	/**
	 * 导出应付汇总
	 * 
	 * @throws IORuntimeException
	 * @throws IOException
	 */
	@Permissions("statistical_004")
	@RequestMapping("/exportSummaryPayable")
	public void exportSummaryPayable() throws IORuntimeException, IOException {
		Map<String, Object> param = RequestUtil.getParameterMap(this.getRequest());
		HttpServletResponse response = this.getResponse();
		List<Map> list = statisticalService.querySummaryPayable(param);
		// 通过工具类创建writer，创建xlsx格式
		ExcelWriter writer = ExcelUtil.getWriter(true);
		writer.setColumnWidth(-1, 20); // 设置列宽
		writer.setOnlyAlias(true); // 只保留别名字段
		// 自定义标题别名
		writer.addHeaderAlias("name", "供应商名称");
		writer.addHeaderAlias("money", "总金额");

		// 一次性写出内容，使用默认样式
		writer.write(list);
		String fileName = URLEncoder.encode("应收汇总", "utf-8") + DateUtil.format(new Date(), "yyyy-MM-dd");
		response.setContentType("application/vnd.ms-excel;charset=utf-8");

		// test.xlsx是弹出下载对话框的文件名，不能为中文，中文请自行编码
		response.setHeader("Content-Disposition", "attachment;filename= " + fileName + ".xlsx");
		response.setHeader("Cache-Control", "private");
		response.setHeader("Pragma", "private");
		response.setHeader("Content-Type", "application/force-download");
		// out为OutputStream，需要写出到的目标流
		writer.flush(response.getOutputStream());
		// 关闭writer，释放内存
		writer.close();
	}
}
